﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Furion.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyProject.Entity;
using MyProject.IService.OrganizationManage;
using MyProject.Model.Param.OrganizationManage;
using MyProject.Util;
using MyProject.Util.Helper;
using MyProject.Util.Model;
using MyProject.Enum.OrganizationManage;

namespace MyProject.Service.OrganizationManage
{
    /// <summary>
    /// 创 建：song
    /// 日 期：2020-12-04 12:41
    /// 描 述：用户信息服务类
    /// </summary>

    public class UserService : IUserService, ITransient
    {
        private readonly IRepository<UserEntity> _userEntityDB;

        public UserService(IRepository<UserEntity> userEntityDB)
        {
            _userEntityDB = userEntityDB;
        }

        #region 获取数据

        /// <summary>
        /// 带条件查询所有
        /// </summary>
        public async Task<List<UserEntity>> GetList(UserListParam param)
        {
            #region 查询条件

            IQueryable<UserEntity> query = _userEntityDB.AsQueryable();
            /*
            // 用户名
            if (!string.IsNullOrEmpty(param.UserName))
                query = query.Where(p => p.UserName.Contains(param.UserName));

            */
            #endregion

            var data = await query.ToListAsync();
            return data;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<List<UserEntity>> GetPageList(UserListParam param, Pagination pagination)
        {
            #region 查询条件

            IQueryable<UserEntity> query = _userEntityDB.AsQueryable();
            /*
            // 用户名
            if (!string.IsNullOrEmpty(param.UserName))
                query = query.Where(p => p.UserName.Contains(param.UserName));

            */
            var data = await query.OrderByDescending(a => a.Id).ToPagedListAsync(pagination.PageIndex, pagination.PageSize);

            #endregion

            // 分页参数赋值
            pagination.TotalCount = data.TotalCount;
            return data.Items.ToList();
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        public async Task<UserEntity> GetEntity(long id)
        {
            var list = await _userEntityDB.AsAsyncEnumerable(p => p.Id == id);
            return list.FirstOrDefault();
        }

        public async Task<int> GetMaxSort()
        {
            object result = await "SELECT MAX(positionSort) FROM UserEntity".SqlNonQueryAsync();
            int sort = result.ParseToInt();
            sort++;
            return sort;
        }

        /// <summary>
        /// 查询多个ID主键数据
        /// </summary>
        public async Task<List<UserEntity>> GetListByIds(string ids)
        {
            if (ids.IsNullOrEmpty())
                throw new Exception("参数不合法！");

            var idArr = TextHelper.SplitToArray<long>(ids, ',').ToList();
            var data = await _userEntityDB.AsAsyncEnumerable(a => idArr.Contains(a.Id.GetValueOrDefault()));

            return data;
        }

        /// <summary>
        /// 根据token获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<OperatorInfo> GetUserByToken(string token)
        {
            if (!SecurityHelper.IsSafeSqlParam(token))
            {
                return null;
            }
            token = token.ParseToString().Trim();

            var strSql = new StringBuilder();
            strSql.Append(@"SELECT  a.Id as UserId,
                                    a.UserStatus,
                                    a.IsOnline,
                                    a.UserName,
                                    a.RealName,
                                    a.Portrait,
                                    a.DepartmentId,
                                    a.ApiToken,
                                    a.IsSystem
                            FROM    SysUser a
                            WHERE  ApiToken = '" + token + "'  ");
            var operatorInfos = await strSql.ToString().SqlQueryAsync<OperatorInfo>();
            if (operatorInfos != null && operatorInfos.Count() > 0)
            {
                var operatorInfo = operatorInfos.First();

                #region 角色

                strSql.Clear();
                strSql.Append(@"SELECT  a.BelongId as RoleId
                                FROM    SysUserBelong a
                                WHERE   a.UserId = " + operatorInfo.UserId + " AND ");
                strSql.Append("         a.BelongType = " + UserBelongTypeEnum.Role.ParseToInt());

                var roleList = await strSql.ToString().SqlQueryAsync<RoleInfo>();
                operatorInfo.RoleIds = string.Join(",", roleList.Select(p => p.RoleId).ToArray());

                #endregion

                #region 部门名称

                strSql.Clear();
                strSql.Append(@"SELECT  a.DepartmentName
                                FROM    SysDepartment a
                                WHERE   a.Id = " + operatorInfo.DepartmentId);
                operatorInfo.DepartmentName = strSql.ToString().SqlQuery<string>().FirstOrDefault();

                #endregion

                return operatorInfo;
            }
            return null;

        }

        public async Task<UserEntity> CheckLogin(string userName)
        {
            var user = await _userEntityDB.Where(t => t.UserName == userName).SingleOrDefaultAsync();
            return user;
        }

        #endregion

        #region 提交数据

        public async Task SaveForm(UserEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                entity.Id = IdGeneratorHelper.Instance.GetId();
                await _userEntityDB.InsertNowAsync(entity);
            }
            else
            {
                await _userEntityDB.UpdateNowAsync(entity, ignoreNullValues: true);
            }
        }

        public async Task DeleteForm(string ids)
        {
            if(string.IsNullOrWhiteSpace(ids))
                throw new Exception("参数不合法！");

            string sql = "Delete From SysUser Where Id in (" + ids + ")";
            await _userEntityDB.SqlNonQueryAsync(sql);
        }


        #endregion

        #region 私有方法

        #endregion
    }
}
